package com.siyue.handler;

import cn.hutool.json.JSONUtil;
import com.siyue.dto.WebCallDto;
import com.siyue.mapper.UserMapper;
import com.siyue.model.User;
import com.siyue.service.CallService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.Objects;

@Component
@Slf4j
public class CallSocketHandler implements WebSocketHandler {
    @Resource
    private CallService callService;

    @Resource
    private UserMapper userMapper;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("I1717857883 {} 开启连接 ", session.getRemoteAddress());
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) {
        log.info(" {} 收到消息 {}", session.getRemoteAddress(),message.getPayload());
        try {
            if ("ping".equals(message.getPayload())) {
                // 收到客户端的ping消息，回复pong
                session.sendMessage(new PongMessage());
                return;
            }
            log.info("I1717857883 收到消息 " +message.getPayload());
            WebCallDto webCallDto = JSONUtil.toBean(message.getPayload().toString(), WebCallDto.class);
            if ("login".equals(webCallDto.getAction())) {
                if (Objects.isNull(webCallDto.getToken())) {
                    session.sendMessage(new TextMessage("{\"action\":\"logout\", \"msg\":\"token不存在\"}"));
                } else {
                    // TODO 判断token是否有效
                    User user = userMapper.selectUserByToken(webCallDto.getToken());
                    if (!Objects.isNull(user)) {
                        SharedData.sessionMap.put(webCallDto.getToken(),session);
                        session.sendMessage(new TextMessage("{\"action\":\"login_success\"}"));
                    } else {
                        session.sendMessage(new TextMessage("{\"action\":\"logout\", \"msg\":\"token不存在\"}"));
                    }
                }
            } else if ("make_call".equals(webCallDto.getAction())) {
                if (Objects.isNull(webCallDto.getToken())|| "".equals(webCallDto.getToken())) {
                    //sessionMap.get(webCallDto.getToken()).sendMessage(new TextMessage("{\"action\":\"logout\", \"msg\":\"token不存在\"}"));
                    session.sendMessage(new TextMessage("{\"action\":\"logout\", \"msg\":\"token不存在\"}"));
                }else if (!SharedData.sessionMap.containsKey(webCallDto.getToken())){
                    //sessionMap.get(webCallDto.getToken()).sendMessage(new TextMessage("{\"action\":\"logout\", \"msg\":\"token不存在\"}"));
                    session.sendMessage(new TextMessage("{\"action\":\"logout\", \"msg\":\"token不存在\"}"));
                } else {
                    //sessionMap.get(webCallDto.getToken());
                    if("".equals(webCallDto.getName())){
                        session.sendMessage(new TextMessage("{\"action\":\"logout\", \"msg\":\"用户姓名不能为空\"}"));
                    }
                    if("".equals(webCallDto.getMobile())){
                        session.sendMessage(new TextMessage("{\"action\":\"logout\", \"msg\":\"拨打手机号不能为空\"}"));
                    }
                    //session.sendMessage(new TextMessage(JSONUtil.toJsonStr(webCallDto)));
                    callService.call(webCallDto.getToken(), webCallDto.getId(), webCallDto.getName(), webCallDto.getMobile());
                }
            }
        } catch (IOException e) {
            log.info("处理消息或发送响应时发生 I/O 异常: " + e.getMessage());
            try {
                session.close(CloseStatus.SERVER_ERROR);
            } catch (IOException closeException) {
                log.info("关闭会话时发生 I/O 异常: " + closeException.getMessage());
            }
        } catch (Exception e) {
            log.info("处理消息时发生未知异常: " + e.getMessage());
            try {
                session.close(CloseStatus.SERVER_ERROR);
            } catch (IOException closeException) {
                log.info("关闭会话时发生 I/O 异常: " + closeException.getMessage());
            }
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception){
        try {
            log.info("I1717857883 {} 失败 {} ", session.getRemoteAddress(), exception.getStackTrace());
            closeSession(session, CloseStatus.SERVER_ERROR);
        } catch (Exception e) {
            System.err.println("错误原因: " + e);
        }

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
        log.info("I1717857883 {} 链接关闭 {} ", session.getRemoteAddress(), closeStatus.toString());
    }
 
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    private void closeSession(WebSocketSession session, CloseStatus status) {
        try {
            if (session.isOpen()) {
                session.close(status);
            }
        } catch (IOException e) {
            System.err.println("Error closing session: " + e.getMessage());
        }
    }
}
